﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace OnlineLibrary.Controllers
{
    public class LoginController : Controller
    {
        //
        // GET: /Login/
        OnlineLibrary.Linq.OnlineLibraryDBDataContext user = new OnlineLibrary.Linq.OnlineLibraryDBDataContext();
        public ActionResult Index()
        {            
            return View();
        }
        [HttpPost]
        //IEnumerable<OnlineLibrary.Linq.tblUser> list = user.tblUsers.ToList();
        public ActionResult Index(OnlineLibrary.Linq.tblUser collection)
        {
            //var exist_user = from e_user in user.tblUsers where e_user.UserName == collection.UserName select e_user;
            
            if (collection.UserName != null && collection.PassWord != null)
            {

                var user_name = from p in user.tblUsers where
                                    p.UserName == collection.UserName &&
                                    p.PassWord == collection.PassWord
                                select p;

                if (user_name.Count() == 0)
                {
                    ViewData["error"] = "Wrong username or password";
                    return View();
                }
                else
                {
                    OnlineLibrary.Linq.tblUser compare = user_name.Single(p => p.UserName == collection.UserName);
                    if (compare.Role == 1)
                    {
                        Session["Admin"] = true;
                        Session["Guest"] = false;
                        return Redirect("/Admin/Index");
                    }
                    else if (compare.Role == 6)
                    {
                        Session["Staff"] = true;
                        Session["Guest"] = false;
                        return Redirect("/User/Index/" + compare.UserId);
                    }
                    else
                    {
                        Session["User"] = true;
                        Session["Guest"] = false;
                        return Redirect("/User/Details/" + compare.UserId);
                    }
                    
                }
                
            }
            else
            {
                ViewData["error"] = "Wrong username or password";
                return View();
            }
            
        }
    }
}
